import express from "express";
import db from "./../libs/DBhelper";
import md5 from "md5";
import fs from "fs";
import path from "path";

let apiRouter = express.Router();

//注册模块
apiRouter.post("/register", (request, response, next) => {

    //把路径用户名,密码保存到数据库
    //准备sql语句
    var sql = "INSERT INTO `userinfo` (`u_tel`,`u_pwd`) VALUES(?,?);";
    // 准备参数
    console.log(request.body)
    let params = [
        request.body.uphone,
        md5(md5(request.body.upwd) + require("./../libs/Configs").keys),
        // request.body.uemail
        // newPath,
    ];
    db.exec(sql, params, (err, result) => {

        if (err) {
            response.json({
                msg: "用户名已存在",
                status: -2,
                err: err.message
            })
            return;
        }
        if (result.affectedRows >= 1) {
            response.json({
                msg: "恭喜注册成功",
                status: 1
            })
        } else {
            response.json({
                msg: "注册失败",
                status: -1
            })
        }

        // if (err) {
        //     response.json({
        //         msg: "注册失败",
        //         status: -2,
        //         err:err.message
        //     })
        //     return;
        // }
        // // else {
        //         response.json({
        //             msg: "注册成功",
        //             status: -1
        //         })
        // }

    })
    //     }
    // })
})

// 登录模块
apiRouter.post("/login", (request, response, next) => {
    let sql = "SELECT u_id,u_tel ";
    sql = sql.concat("FROM userinfo WHERE  u_status=1 AND u_tel=? AND u_pwd=? ;");
    console.log(sql)
    let params = [
        request.body.uphone,
        md5(md5(request.body.upwd) + require("./../libs/Configs").keys)
    ]
    console.log(params)

    db.exec(sql, params, (err, result) => {
        console.log(result)
        if (err) {
            response.json({
                msg: "登录失败",
                err: err.message,
                status: -2
            })
            return;
        }
        if (result.length >= 1) {
            response.json({
                msg: "登录成功",
                status: 1,
                data: result[0]
            })
        } else {
            response.json({
                msg: "登录失败,用户名或密码错误",
                status: -1
            })
        }
    })
})

// 产品列表
apiRouter.get("/product", (request, response, next) => {
    var goodsStr = fs.readFileSync("./data/list.json").toString();
    response.end(goodsStr)
})

apiRouter.get("/productinfo/:id", (request, response, next) => {
    var goodsStr = fs.readFileSync("./data/list.json").toString();
    var resultObj = JSON.parse(goodsStr).filter((el) => {
        return el.p_id == request.params.id
    })

    response.json(resultObj)
})
// 加入购物车
apiRouter.post("/addcart", (request, response, next) => {
    //异常捕获

    try {
        //     // 1.根据用户名和商品id查询该数据是否存在
        let querySelect = "SELECT * FROM `carts` WHERE  u_id=? AND p_id=?";
        let queryParams = [
            request.body.u_id,
            request.body.p_id
        ]
        db.exec(querySelect, queryParams, (err, queryResult) => {
            // 查询返回结果,结果是一个数组length属性
            if (queryResult.length >= 1) {
                let uplateSql = "UPDATE `carts` SET p_num=p_num+?,p_total=p_num*p_price WHERE u_id=? AND p_id=?;";
                let updateParams = [
                    request.body.p_num,
                    request.body.u_id,
                    request.body.p_id
                ]
                db.exec(uplateSql, updateParams, (err, updateResult) => {
                    if (updateResult.affectedRows == 1) {
                        response.json({
                            msg: "加入购物车成功u",
                            status: 1
                        })
                    } else {

                        response.json({
                            msg: "加入购物车失败",
                            status: -1
                        })
                    }

                })
            } else {
                // 加入数据库需要准备哪些参数?
                // 商品的id,用户名id,商品名称,商品价格,商品数量,商品图片,商品总价
                let sql = "INSERT INTO `carts` (`u_id`,`p_id`,`p_name`,`p_price`,`p_num`,`p_img`,`p_total`)VALUES(?,?,?,?,?,?,?);";

                let params = [
                    request.body.u_id,
                    request.body.p_id,
                    request.body.p_name,
                    request.body.p_price,
                    request.body.p_num,
                    request.body.p_img_index,
                    request.body.p_price * request.body.p_num
                ]
                db.exec(sql, params, (err, result) => {
                    if (err) {
                        response.json({
                            msg: "加入购物车失败insert",
                            status: -1,
                            err: err.message
                        })
                        return;
                    }
                    if (result.affectedRows >= 1) {
                        response.json({
                            msg: "加入购物车成功insert",
                            status: 1
                        })
                    }
                })
            }

        });
    } catch (err) {
        response.json({
            msg: "加入失败",
            err: err.message,
            status: -2
        })
    }
})

apiRouter.get("/getCarts", (request, response, next) => {
    let sql = "SELECT * FROM `carts` WHERE`u_id`=?";
    let params = [
        request.query.u_id
    ]
    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "拉取购物车失败",
                status: -2,
                err: err.message
            })
            return;
        } else {
            response.json({
                msg: "完成拉取",
                status: 1,
                data: result
            })
        }
    })
})
// 购物车列表对某个产品加减操作
apiRouter.post("/modify", (request, response, next) => {
    let uplateSql = "UPDATE `carts` SET p_num=?,p_total=p_num*p_price WHERE c_id=? ";
    // console.log(request.body.p_num)
    let updateParams = [
        request.body.p_num,
        request.body.c_id
    ]
    db.exec(uplateSql, updateParams, (err, updateResult) => {
        if (err) {
            response.json({
                msg: "加入购物车失败u",
                status: -1,
                err: err.message
            })
            return;
        }
        if (updateResult.affectedRows == 1) {
            response.json({
                msg: "加入购物车成功",
                status: 1
            })
        }

    })

})
//删除
apiRouter.post("/delete",async (request, response, next) => {
    let sql = "DELETE FROM carts WHERE c_id=?;";
    let params = [request.body.c_id];
    let result = await db.execAsync(sql, params).catch((err) => {
        response.json({
            msg:"删除失败",
            err:err.message
        })
    })
    if(result.affectedRows==1){
        response.json({
            msg:"删除成功",
            status:1
        })
    }else{
        response.json({
            msg:"删除失败"
        })
    }
})
module.exports = {
    apiRouter
}